package com.tuozixuan.forest.api.impl;

import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import com.dtflys.forest.Forest;
import com.dtflys.forest.callback.OnSuccess;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.tuozixuan.forest.api.Test2Api;
import com.tuozixuan.forest.dto.UserDTO;
import com.tuozixuan.forest.external.UserExternalApi;

@RestController
public class Test2ApiImpl implements Test2Api {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private UserExternalApi userExternalApi;


	@Override
	public String getUserNameById(String id) {
		return Forest.get("http://localhost:8080/user/getUserNameById?id=" + id).executeAsString();
	}

	@Override
	public List<String> getUserNamesByIds(String[] ids) {
		
		return Forest.get("http://localhost:8080/user/getUserNamesByIds").addQuery("ids", Arrays.asList(ids)).executeAsList();
	}

	@Override
	public boolean addUser() {
		UserDTO userDTO = new UserDTO();
		userDTO.setId("1");
		userDTO.setUserName("lisi");
		return userExternalApi.addUser(userDTO);
	}
	
	@Override
	public boolean addUser2() {
		return userExternalApi.addUser2("1", "lisi");
	}

	@Override
	public boolean addUserWithException() {
		UserDTO userDTO = new UserDTO();
		userDTO.setId("1");
		userDTO.setUserName("lisi");
		return userExternalApi.addUserWithException2(userDTO);
	}

	@Override
	public boolean asyncAddUser() {
		UserDTO userDTO = new UserDTO();
		userDTO.setId("1");
		userDTO.setUserName("lisi");
		userExternalApi.asyncAddUser(userDTO);
		logger.info("asyncAddUser call finish");
		return true;
	}

	@Override
	public boolean asyncAddUserAndGet() {
		UserDTO userDTO = new UserDTO();
		userDTO.setId("1");
		userDTO.setUserName("lisi");
		userExternalApi.asyncAddUserAndGet(userDTO, new OnSuccess<Boolean>(){
			@Override
			public void onSuccess(Boolean data, ForestRequest req, ForestResponse res) {
				logger.info("result:{}", data);
			}
		}, null);
		logger.info("asyncAddUser call finish");
		return true;
	}

}
